{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn import datasets\n",
    "import pandas as pd\n",
    "\n",
    "# Load the boston house-prices dataset (regression).\n",
    "boston = datasets.load_boston()\n",
    "boston_target_name = 'MEDV'\n",
    "boston_features_names = boston.feature_names\n",
    "boston_df = pd.DataFrame(boston.data, columns=boston_features_names)\n",
    "boston_df[boston_target_name] = boston.target"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.pipeline import Pipeline\n",
    "from sklearn.model_selection import train_test_split\n",
    "from xgboost import XGBRegressor\n",
    "\n",
    "seed = 123456\n",
    "X, y = boston_df[boston_features_names], boston_df[boston_target_name]\n",
    "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=seed)\n",
    "\n",
    "pipeline = Pipeline([\n",
    "    ('Xgbr', XGBRegressor(objective='reg:linear',\n",
    "                          colsample_bytree=0.3,\n",
    "                          learning_rate=0.1,\n",
    "                          max_depth=3,\n",
    "                          alpha=10,\n",
    "                          n_estimators=10,\n",
    "                          seed=seed))\n",
    "])\n",
    "pipeline.fit(X_train, y_train)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Predict the first row of test data, the result should be identical to one produced by PMML\n",
    "print(X_test.head(1))\n",
    "pipeline.predict(X_test.head(1))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from nyoka import xgboost_to_pmml\n",
    "\n",
    "# Export the pipeline model into PMML\n",
    "model = 'xgbr_pmml.pmml'\n",
    "xgboost_to_pmml(pipeline, boston_features_names, boston_target_name, model)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from daas_client import DaasClient\n",
    "\n",
    "# Please, change to your URL of Daas server, and credentials\n",
    "url = 'https://192.168.64.3:31753'\n",
    "username = 'admin'\n",
    "password = 'password'\n",
    "project = 'Examples'\n",
    "\n",
    "# Initiate a client of DaaS server, and set the created \"Examples\" project\n",
    "client = DaasClient(url, username, password)\n",
    "if not client.project_exists(project):\n",
    "    client.create_project(project, 'examples', 'This is an example project')\n",
    "client.set_project(project)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from pprint import pprint\n",
    "\n",
    "model_name = 'pmml-reg'\n",
    "\n",
    "# Publish the built model into DaaS\n",
    "publish_resp = client.publish(model,\n",
    "                              name=model_name,\n",
    "                              mining_function='regression',\n",
    "                              x_test=X_test,\n",
    "                              y_test=y_test,\n",
    "                              description='A PMML regression model')\n",
    "pprint(publish_resp)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Try to test the published model\n",
    "test_resp = client.test(model_name, model_version=publish_resp['model_version'])\n",
    "pprint(test_resp)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Call the test REST API above, 'model_name' is required in payload because the test runtime serves multiple models \n",
    "# in a project. \n",
    "import requests\n",
    "\n",
    "bearer_token = 'Bearer {token}'.format(token=test_resp['access_token'])\n",
    "payload = {\n",
    "    'args': {'X': [{'AGE': 89.5,\n",
    "                    'B': 396.9,\n",
    "                    'CHAS': 0.0,\n",
    "                    'CRIM': 22.5971,\n",
    "                    'DIS': 1.5184,\n",
    "                    'INDUS': 18.1,\n",
    "                    'LSTAT': 31.99,\n",
    "                    'NOX': 0.7,\n",
    "                    'PTRATIO': 20.2,\n",
    "                    'RAD': 24.0,\n",
    "                    'RM': 5.0,\n",
    "                    'TAX': 666.0,\n",
    "                    'ZN': 0.0}],\n",
    "             'model_name': model_name,\n",
    "             'model_version': publish_resp['model_version']}}\n",
    "\n",
    "response = requests.post(test_resp['endpoint_url'],\n",
    "                         headers={'Authorization': bearer_token},\n",
    "                         json=payload,\n",
    "                         verify=False)\n",
    "pprint(response.json())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Deploy the published model into product\n",
    "deploy_resp = client.deploy(model_name, \n",
    "                            deployment_name=model_name + '-svc',\n",
    "                            model_version=publish_resp['model_version'])\n",
    "pprint(deploy_resp)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Call the product REST API above, the deployment runtime(s) serve the deployed model dedicatedly.\n",
    "deploy_bearer_token = 'Bearer {token}'.format(token=deploy_resp['access_token'])\n",
    "deploy_payload = {'args': {'X': [{'AGE': 89.5,\n",
    "                                  'B': 396.9,\n",
    "                                  'CHAS': 0.0,\n",
    "                                  'CRIM': 22.5971,\n",
    "                                  'DIS': 1.5184,\n",
    "                                  'INDUS': 18.1,\n",
    "                                  'LSTAT': 31.99,\n",
    "                                  'NOX': 0.7,\n",
    "                                  'PTRATIO': 20.2,\n",
    "                                  'RAD': 24.0,\n",
    "                                  'RM': 5.0,\n",
    "                                  'TAX': 666.0,\n",
    "                                  'ZN': 0.0}]}}\n",
    "\n",
    "response = requests.post(deploy_resp['endpoint_url'],\n",
    "                         headers={'Authorization': deploy_bearer_token},\n",
    "                         json=deploy_payload,\n",
    "                         verify=False)\n",
    "pprint(response.json())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
